﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.ServiceModel;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using MF.Data;

namespace MF.ServiceModel
{
    public class DbContextBehavior : Attribute, IContractBehavior
    {
        public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
        {
            dispatchRuntime.InstanceContextInitializers.Add(new DbContextInitializer());
        }

        #region IContractBehavior not implemented Members

        public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { }
        public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime) { }
        public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint) { }

        #endregion
    }

    public class DbContextInitializer : IInstanceContextInitializer
    {
        public void Initialize(InstanceContext instanceContext, Message message)
        {
            instanceContext.Extensions.Add(new DbContextInstanceExtension());
        }
    }

    public class DbContextInstanceExtension : IExtension<InstanceContext>
    {
        public DbContextInstanceExtension() { }
        public void Attach(InstanceContext owner) { }
        public void Detach(InstanceContext owner) { }

        public IDbContext Context { get; set; }
    }
}
